//
//  TranslateVC.m
//  Imagedemo
//
//  Created by 文杰 许                       on 2018/3/29.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

#import "TranslateVC.h"

@interface TranslateVC ()

@end

@implementation TranslateVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //开始绘画
    UIGraphicsBeginImageContext(self.view.bounds.size);
    CGContextRef con = UIGraphicsGetCurrentContext();
    
    //设置颜色
    [[UIColor redColor] setFill];
    
    //绘画
    CGRect rect = CGRectMake(-5, 0, 10, -50);
    CGContextTranslateCTM(con, 10, 200);
    [self goStraight:con rect:rect offset:20];
    [self turnDirection:con rect:rect angle:30 count:3];
    [self goStraight:con rect:rect offset:20];
    //把旋转点从一个方向移到另外一个方向，注意需要用CGContextScaleCTM把Y轴颠倒
    CGContextTranslateCTM(con, 0, -50);
    CGContextScaleCTM(con, 1, -1);
    [self turnDirection:con rect:rect angle:30 count:3];
    [self goStraight:con rect:rect offset:20];
    
    //结束画图
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageV = [[UIImageView alloc] initWithImage:image];
    [self.view addSubview:imageV];
}

//使用CGContextTranslateCTM并连续画6个方格
- (void)goStraight:(CGContextRef)con rect:(CGRect)rect offset:(CGFloat)offset
{
    for (int i = 0; i < 6; i++)
    {
        CGContextTranslateCTM(con, offset, 0);
        CGContextFillRect(con, rect);
    }
}

//使用CGContextRotateCTM旋转并画指定个数的方格
- (void)turnDirection:(CGContextRef)con rect:(CGRect)rect angle:(CGFloat)angle count:(NSInteger)count
{
    for (int i = 0; i < count; i++)
    {
        CGContextRotateCTM(con, angle * M_PI / 180);
        CGContextFillRect(con, rect);
    }
}

@end
